package google.architecture.coremodel.viewmodel;

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.List;

import google.architecture.coremodel.datamodel.http.entities.ShoppingCarItem;
import google.architecture.coremodel.navigator.ShoppingCarNavigator;
import google.architecture.coremodel.util.DoubleMathUtil;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 保存生命周期和UI所使用的数据
 * Created by dxx on 2017/11/10.
 */

public class ShoppingCarViewModel extends PaymentViewModel {
    public static final int ACTION_ADD = 0;
    public static final int ACTION_REDUCE = 1;
    //生命周期观察的数据
    private LiveData<List<ShoppingCarItem>> mLiveObservableData;
    //UI使用可观察的数据 ObservableField是一个包装类
    public ObservableField<List<ShoppingCarItem>> uiObservableData = new ObservableField<>();

    public ObservableField<Integer> totalCountField = new ObservableField<>();
    public ObservableField<Double> totalPriceField = new ObservableField<>();
    public ObservableBoolean countDownShow = new ObservableBoolean();

    private ShoppingCarNavigator mNavigator;

    public ShoppingCarViewModel(@NonNull Application application) {
        super(application);
        totalCountField.set(0);
        totalPriceField.set(0.0);
        countDownShow.set(false);
        loadData();
    }

    public void setShoppingCarNavigator(ShoppingCarNavigator navigator) {
        super.setNavigator(navigator);
        mNavigator = navigator;
    }

    public void loadData() {
        MutableLiveData<List<ShoppingCarItem>> applyData = new MutableLiveData<>();
        mAutoVenderDataRepository.getShoppingCarListRepository()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<ShoppingCarItem>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(List<ShoppingCarItem> value) {
                        int totalCount = 0;
                        double totalPrice = 0;
                        for (ShoppingCarItem item : value) {
                            totalCount += item.getCount();
                            double prices = item.getPrice() * item.getCount();
                            totalPrice = DoubleMathUtil.add(totalPrice, prices);

                        }
                        totalCountField.set(totalCount);
                        totalPriceField.set(totalPrice);
                        applyData.setValue(value);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
        mLiveObservableData = applyData;
    }


    public void clearData(boolean isFinish) {
        MutableLiveData<List<ShoppingCarItem>> applyData = new MutableLiveData<>();
        final List<ShoppingCarItem> shoppingCarItemList = mLiveObservableData.getValue();
        if (shoppingCarItemList != null && !shoppingCarItemList.isEmpty()) {
            ShoppingCarItem[] shoppingCarItems = shoppingCarItemList.toArray(new ShoppingCarItem[shoppingCarItemList.size()]);
            mAutoVenderDataRepository.deleteShoppingCar(shoppingCarItems)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean s) {
                            mAppConfigHelper.saveHasData(false);
                            mNavigator.onClearAllData(isFinish);
                            totalCountField.set(0);
                            totalPriceField.set(0.0);
                        }
                    });
        }
        mLiveObservableData = applyData;
    }

    public void deleteShoppingCar(ShoppingCarItem item) {
        mAutoVenderDataRepository.deleteShoppingCar(item)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean s) {
                        Log.d(TAG, "deleteShoppingCar success!");
                        int totalCount = totalCountField.get() - item.getCount();
                        double totalPrice = DoubleMathUtil.add(totalPriceField.get(), -item.getCount() * item.getPrice());
                        totalCountField.set(totalCount);
                        totalPriceField.set(totalPrice);
                        mAppConfigHelper.saveHasData(totalCount > 0);
                    }
                });
    }

    public void updateShoppingCar(ShoppingCarItem item, int action) {
        mAutoVenderDataRepository.updateShoppingCar(item)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean s) {
                        Log.d(TAG, "updateShoppingCar success!");
                        double totalPrice = 0;
                        int totalCount = 0;
                        if (action == ACTION_ADD) {
                            totalPrice = DoubleMathUtil.add(totalPriceField.get(), item.getPrice());
                            totalCount = totalCountField.get() + 1;
                        } else if (action == ACTION_REDUCE) {
                            totalPrice = DoubleMathUtil.add(totalPriceField.get(), -item.getPrice());
                            totalCount = totalCountField.get() - 1;
                        }
                        totalCountField.set(totalCount);
                        totalPriceField.set(totalPrice);
                    }
                });
    }


    /**
     * LiveData支持了lifecycle生命周期检测
     *
     * @return
     */
    public LiveData<List<ShoppingCarItem>> getLiveObservableData() {
        return mLiveObservableData;
    }

    /**
     * 设置
     *
     * @param shoppingCarItems
     */
    public void setUiObservableData(List<ShoppingCarItem> shoppingCarItems) {
        this.uiObservableData.set(shoppingCarItems);
    }
}
